package com.sf.iisp.scheduler;

import com.sf.iisp.scheduler.task.ReserveBindingTask;
import com.sf.iisp.scheduler.task.ReserveUnbindingTask;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.scheduling.concurrent.ThreadPoolTaskScheduler;

/**
 * Created by qi on 16-7-6.
 */
public class ReserveScheduler implements InitializingBean {

    @Autowired
    private ThreadPoolTaskScheduler taskScheduler;
    @Autowired
    private RedisTemplate<String, Object> redisTemplate;

    @Value("${redis.binding.key.prefix:binding-}")
    private String bindKeyPrefix;

    @Value("${redis.unbinding.key.prefix:unbinding-}")
    private String unbindKeyPrefix;

    @Value("${redis.listener.binding.patter:usr:binding}")
    private String bindTopic;

    @Value("${redis.listener.unbinding.pattern:usr:unbinding}")
    private String unbindTopic;

    @Value("${redis.scheduler.enabled:false}")
    private Boolean enabled = false;

    @Override
    public void afterPropertiesSet() throws Exception {
//        System.out.println("Running ?");
//        BindingRecord br = new BindingRecord();
//        br.setSysCode("IISP");
//        br.setCourierPhone("13999999999");
//        BindingRecord br1 = new BindingRecord();
//        br1.setSysCode("IISP1");
//        br1.setCourierPhone("139999999991");
//        List<BindingRecord> brs = new ArrayList<BindingRecord>();
//        brs.add(br);
//        brs.add(br1);
//        redisTemplate.opsForList().leftPush("test1", br);
//        redisTemplate.opsForList().leftPush("test1", br1);
//
//        //TODO;保存在配置文件中。
//        String keyProfiex = "binding-";
//        String topic = "usr:binding";

        if (enabled) {
            //TODO:  redisTemplate.opsForList().leftPush("test1", br); 保存元素，key格式：binding-2016-01-01 12:12，value: BindingRecord
            taskScheduler.scheduleAtFixedRate(new ReserveBindingTask(redisTemplate, bindKeyPrefix, bindTopic), 60000L);
            taskScheduler.scheduleAtFixedRate(new ReserveUnbindingTask(redisTemplate, unbindKeyPrefix, unbindTopic), 60000L);
        }
    }
}
